package deyi.udp;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

@Component("udpclient")
@Scope(value = "prototype")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UdpClient{

    @NonNull private String hostName;
    @NonNull private int port;
    private byte[] data;

    @Async
    public void sendUdpData(String host, int localPort, int remotePort, byte[] data) throws Exception{
        DatagramSocket socket = new DatagramSocket(localPort);
        InetAddress address = InetAddress.getByName(host);
        DatagramPacket packet = new DatagramPacket(data, data.length, address, remotePort);
        socket.send(packet);
        socket.close();
    }

}
